package com.jldt.flutter_douyin;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;

import com.bytedance.sdk.open.aweme.authorize.model.Authorization;
import com.bytedance.sdk.open.aweme.base.ImageObject;
import com.bytedance.sdk.open.aweme.base.MediaContent;
import com.bytedance.sdk.open.douyin.DouYinOpenApiFactory;
import com.bytedance.sdk.open.douyin.DouYinOpenConfig;
import com.bytedance.sdk.open.douyin.ShareToContact;
import com.bytedance.sdk.open.douyin.api.DouYinOpenApi;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;

public class FlutterMethodChannel implements MethodChannel.MethodCallHandler {
    public static final String CHANNEL_NAME = "flutter_douyin";
    public static final String INVOKE_NAME = "ANDROID_DouyinOpenSDKAuthRequest";
    public static final String TAG = "flutter_douyin";

    private MethodChannel channel;
    private Activity activity;


    private static volatile FlutterMethodChannel instance;

    private FlutterMethodChannel() {
    }

    public static FlutterMethodChannel getInstance() {
        if (instance == null) {
            synchronized (FlutterMethodChannel.class) {
                if (instance == null) {
                    instance = new FlutterMethodChannel();
                    Log.e("FlutterMethodChannel...", "[完成]");
                }
            }
        }
        return instance;
    }

    public void init(@NonNull Activity activity, @NonNull BinaryMessenger messenger) {
        this.activity = activity;
        channel = new MethodChannel(messenger, CHANNEL_NAME);
        channel.setMethodCallHandler(this);


    }

    public void invokeMethod(@NonNull Object arguments) {
        if (channel != null) {
            channel.invokeMethod(INVOKE_NAME, arguments);
        }
    }


    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
        if (call.method.equals("getPlatformVersion")) {
            result.success("Android " + android.os.Build.VERSION.RELEASE + "  " + activity.getPackageName());
        } else if (call.method.equals("setPlatformKey")) {
            String androidKey = call.argument("androidKey");
            DouYinOpenApiFactory.init(new DouYinOpenConfig(androidKey));
            result.success(androidKey);
        } else if (call.method.equals("douyinOpenSDKAuthRequest")) {

            List<String> permissionMest = call.argument("permissionMest");
            List<String> permissionOptional = call.argument("permissionOptional");

            DouYinOpenApi douyinOpenApi = DouYinOpenApiFactory.create(activity);
            Authorization.Request request = new Authorization.Request();
            request.scope = permissionMest.toString().replace("[", "").replace("]", "");

            if (permissionOptional != null) {
                if (!permissionOptional.isEmpty()) {
                    request.optionalScope1 = permissionOptional.toString().replace("[", "").replace("]", "");
                    Log.e(TAG, request.optionalScope1);
                }
            }
            request.callerLocalEntry = "com.jldt.flutter_douyin.douyinapi.DouYinEntryActivity";

            Log.e(TAG, request.scope);


            douyinOpenApi.authorize(request);
            result.success("success");
        } else if (call.method.equals("isDouYinInstalled")) {
            result.success(isAnyDouYinInstalled(activity.getApplicationContext()));
        } else if (call.method.equals("shareImage")) {
            DouYinOpenApi douyinOpenApi = DouYinOpenApiFactory.create(activity);
            // 初始化资源路径，路径请提供绝对路径
            ShareToContact.Request request = new ShareToContact.Request();
            ArrayList<String> mUri = new ArrayList<>();
            String fileUri = getFileUri(call.argument("path"));
            Log.d("测试", "地址： " + fileUri);
            mUri.add(fileUri);// 注意： 只能传入一张图片，目前只支持单图且为本地图片 //分享单图
            ImageObject imageObject = new ImageObject();
            imageObject.mImagePaths = mUri;
            MediaContent mediaContent = new MediaContent();
            mediaContent.mMediaObject = imageObject;
            request.mMediaContent = mediaContent;
            //判断是否可以分享到联系人
            if (douyinOpenApi.isAppSupportShareToContacts()) {
                // 调起分享
                douyinOpenApi.shareToContacts(request);
            } else {
                Toast.makeText(activity, "未安装相关app", Toast.LENGTH_LONG).show();
            }

        } else if (call.method.equals("shareNative")) {
            //TODO 待适配不同类型的文件
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("image/*");
            shareIntent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(activity,
                    "com.dc.jiachao.fileprovider", new File(call.argument("path").toString())));
            shareIntent.putExtra(Intent.EXTRA_SUBJECT, "分享的内容");
            activity.startActivity(Intent.createChooser(shareIntent, "分享到"));
        } else {
            result.notImplemented();
        }

    }

    public String getFileUri(String filePath) {
        // 该filePath对应于xml/file_provider_paths里的第一行配置：，因此才可被共享
        File file = new File(filePath);
        // 使用contentPath作为文件路径进行分享
        // 要与`AndroidManifest.xml`里配置的`authorities`一致，假设你的应用包名为com.example.app
        Uri contentUri = FileProvider.getUriForFile(activity,
                "com.dc.jiachao.fileprovider", file);
        activity.grantUriPermission("com.ss.android.ugc.aweme",
                contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
        activity.grantUriPermission("com.ss.android.ugc.aweme.lite",
                contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
        return contentUri.toString();   // contentUri.toString() 即是以"content://"开头的用于共享的路径
    }

    private boolean isAnyDouYinInstalled(Context context) {
        String[] pkgList = {
                "com.ss.android.ugc.aweme",      // 抖音
                "com.ss.android.ugc.aweme.lite"// 抖音极速版
        };
        PackageManager pm = context.getPackageManager();
        for (String pkg : pkgList) {
            try {
                pm.getPackageInfo(pkg, 0);
                return true;
            } catch (PackageManager.NameNotFoundException e) {
                // 没找到，继续查下一个
            }
        }
        return false;
    }

}

